import { createApp } from "vue";
import App from "./App.vue";
import Antd from "ant-design-vue";
import "ant-design-vue/dist/antd.css";
import * as antdIcons from "@ant-design/icons-vue";
import router from "./router";
import { createPinia } from "pinia";
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";
import axios from "axios";
import dayjs from "dayjs";
import pkg from "../package.json";
import { useMainStore } from "@/store/index.js";

const app = createApp(App);

import "./mock/index.js";

axios.defaults.baseURL = import.meta.env.VITE_APP_BASE_API;
// 添加请求拦截器，在请求头中加token
axios.interceptors.request.use(
  (config) => {
    const store = useMainStore();
    const token = store.$state._token;
    if (token) {
      config.headers.Authorization = "Bearer " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 添加返回拦截器，判断是否401
axios.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response) {
      const { status, data } = error.response;
      switch (status) {
        case 401:
          // 服务器端返回401，说明Token已无效
          const store = useMainStore();
          store.loginOut();
          router.replace({
            path: "/login",
            query: {
              redirect: router.currentRoute.fullPath,
            },
          });
          break;
      }

      if (data && data.Message) {
        message.error(data.Message);
      }
      return Promise.reject(data);
    }
  }
);
app.config.globalProperties.$axios = axios;

Object.keys(antdIcons).forEach((key) => {
  app.component(key, antdIcons[key]);
});
app.config.globalProperties.$antdIcons = antdIcons;

const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
app.use(Antd).use(router).use(pinia).mount("#app");

const copyRightConsole = (packageInfo) => {
  /* 内容代码 */
  const projectName = packageInfo.name || "";
  const description = packageInfo.description || "";
  const version = `版 本 号：${packageInfo.version}`;
  const dateTime = `编译日期：${dayjs().format("YYYY-MM-DD HH:mm:ss")}`;

  // 空格有意义，不要格式化
  console.log(
    `%c${projectName} 
%c${description} 
%c${version}
${dateTime}`,
    "font-size: 20px;font-weight: 300;color: #ff0000;",
    "padding:4px 0;color: #000000;",
    "color: rgb(30,152,255);padding:4px 0;"
  );
};

if (window.console) {
  copyRightConsole(pkg);
}
